package com.jiangxiaofei.citycloud.activity.freshfruits;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.EmptyUtils;
import com.google.gson.Gson;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.adapter.VillagePublishHeaderPhotoAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.GoodIdBean;
import com.jiangxiaofei.citycloud.bean.JsonBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.IntConstants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.FreshConstant;
import com.jiangxiaofei.citycloud.mvp.FreshPersenter;
import com.jiangxiaofei.citycloud.mvp.MainConstant;
import com.jiangxiaofei.citycloud.mvp.MainPersenter;
import com.jiangxiaofei.citycloud.param.GoodsPublicParam;
import com.jiangxiaofei.citycloud.param.UpLoadPhotoParam;
import com.jiangxiaofei.citycloud.util.GetJsonDataUtil;
import com.jiangxiaofei.citycloud.util.PickerImageLoader;
import com.jiangxiaofei.citycloud.view.SlidingRecyclerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @author: JiangXFei
 * @date: 2017/11/23 0023
 * @content: 果蔬发布页面
 */

public class FreshFruitsGoodPublishActivity extends BaseActivity
        implements FreshConstant.PutFreshGoodView, MainConstant.UpLoadPhotoView {
    public static final int SHOWADDPHOTO = 0x0001;
    public static final int HIDEADDPHOTO = 0x0002;
    private static final int IMAGE_PICKER = 0X0003;
    public static final int TYPERESULT = 0X0004;

    private static final int MSG_LOAD_DATA = 0x0005;
    private static final int MSG_LOAD_SUCCESS = 0x0006;
    private static final int MSG_LOAD_FAILED = 0x0007;
    @InjectView(R.id.tv_add_photo)
    TextView tvAddPhoto;
    @InjectView(R.id.img_add_photo)
    ImageView imgAddPhoto;
    @InjectView(R.id.img_add_photo_litter)
    ImageView imgAddPhotoLitter;
    @InjectView(R.id.recy_photo_list)
    SlidingRecyclerView recyPhotoList;
    @InjectView(R.id.hsv_photo_list)
    HorizontalScrollView hsvPhotoList;
    @InjectView(R.id.et_flea_title)
    EditText etFleaTitle;
    @InjectView(R.id.et_flea_content)
    EditText etFleaContent;
    @InjectView(R.id.tv_good_type)
    TextView tvGoodType;
    @InjectView(R.id.linear_select_type)
    LinearLayout linearSelectType;
    @InjectView(R.id.tv_good_price)
    EditText tvGoodPrice;
    @InjectView(R.id.linear_select_price)
    LinearLayout linearSelectPrice;
    @InjectView(R.id.tv_good_location)
    TextView tvGoodLocation;
    @InjectView(R.id.linear_select_location)
    LinearLayout linearSelectLocation;
    @InjectView(R.id.btn_publish)
    Button btnPublish;

    private ArrayList<ImageItem> images = new ArrayList<>();
    private int goodTypeId = 0;
    private List<String> imgs = new ArrayList<>();
    private MainConstant.UploadPhotoPersenter uploadPhotoPersenter;
    private FreshConstant.PutFreshGoodPersenter putFreshGoodPersenter;
    private UpLoadPhotoParam loadPhotoParam;
    private GoodsPublicParam goodsPublicParam = new GoodsPublicParam();
    private BDLocation bdLocation;
    private String lat;
    private String lng;
    private Intent intent;
    private VillagePublishHeaderPhotoAdapter photoAdapter;
    private Thread thread;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOWADDPHOTO:
                    //显示添加图片
                    hsvPhotoList.setVisibility(View.GONE);
                    tvAddPhoto.setVisibility(View.VISIBLE);
                    break;
                case HIDEADDPHOTO:
                    hsvPhotoList.setVisibility(View.VISIBLE);
                    tvAddPhoto.setVisibility(View.GONE);
                    int position = (int) msg.obj;
                    imgs.remove(position);
                    //隐藏添加图片
                    break;
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    break;

                case MSG_LOAD_FAILED:
                    break;

                default:
                    break;
            }
        }
    };

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private GoodIdBean goodIdBean;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_fresh_fruits_good_publish_layout);
        ButterKnife.inject(this);
        mActivity = this;
        mContext = this;
        initPicker();
        initTitle();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        recyPhotoList.setLayoutManager(linearLayoutManager);
        uploadPhotoPersenter = new MainPersenter(mContext, (MainConstant.UpLoadPhotoView) mActivity);
        putFreshGoodPersenter = new FreshPersenter(mContext, (FreshConstant.PutFreshGoodView) mActivity);
        if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
            bdLocation = Constants.bdLocation;
        } else {
            Constants.bdclient.start();
            bdLocation = Constants.bdLocation;
        }
        lat = String.valueOf(bdLocation.getLatitude());
        lng = String.valueOf(bdLocation.getLongitude());
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        setLeftOneBg(R.drawable.ic_back_black);
        setCTitle("发布宝贝");
        mCenterTitle.setTextColor(Color.parseColor("#7b7b7b"));
        rl_layout.setBackgroundColor(Color.parseColor("#ffffff"));
    }

    @OnClick({R.id.btn_publish, R.id.linear_select_type, R.id.linear_select_location,
            R.id.img_add_photo, R.id.tv_add_photo, R.id.img_add_photo_litter})
    public void bOnClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.img_add_photo:
            case R.id.tv_add_photo:
            case R.id.img_add_photo_litter:
                //添加图片
                imgs.clear();
                intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                break;
            case R.id.btn_publish:
                //发布
                if (isForm()) {
                    putFreshGoodPersenter.putFreshGood();
                }
                break;
            case R.id.linear_select_type:
                //选择商品类型
                intent = new Intent(mContext, FreshFruitsCassifySelectActivity.class);
                startActivityForResult(intent, IntConstants.FRESHSELECTCASSIFYID);
                break;
            case R.id.linear_select_location:
                //选择产地
                ShowPickerView(tvGoodLocation);
                break;
        }
    }

    /**
     * 初始化图片裁剪器
     */
    private void initPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickerImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(9);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    /**
     * 鲁班图片压缩
     *
     * @param photos
     */
    private void lubanImg(String photos) {
        Luban.with(this)
                .load(photos)
                .setCompressListener(new OnCompressListener() {

                    @Override
                    public void onStart() {
                        // 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        //  压缩成功后调用，返回压缩后的图片文件
                        loadPhotoParam = new UpLoadPhotoParam(file);
                        uploadPhotoPersenter.uploadData();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩
    }

    /**
     * 表单验证
     */
    public boolean isForm() {
        String title = etFleaTitle.getText().toString();
        String content = etFleaContent.getText().toString();
        String price = tvGoodPrice.getText().toString();
        String location = tvGoodLocation.getText().toString();
        if (EmptyUtils.isEmpty(title)) {
            Toast.makeText(mContext, "请输入宝贝标题!", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (EmptyUtils.isEmpty(content)) {
            Toast.makeText(mContext, "请输入宝贝描述", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (goodTypeId == -1) {
            Toast.makeText(mContext, "请选择宝贝分类", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (EmptyUtils.isEmpty(price)) {
            Toast.makeText(mContext, "请输入宝贝价格", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (EmptyUtils.isEmpty(location)) {
            Toast.makeText(mContext, "请输入商品产地", Toast.LENGTH_SHORT).show();
            return false;
        }
        goodsPublicParam.setAuthor(Constants.userId);
        goodsPublicParam.setLat(lat);
        goodsPublicParam.setLng(lng);
        goodsPublicParam.setTitle(title);
        goodsPublicParam.setPrice(price);
        goodsPublicParam.setProarea(location);
        goodsPublicParam.setDescrption(content);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < imgs.size(); i++) {
            stringBuffer.append(imgs.get(i));
            if (i < imgs.size() - 1) {
                stringBuffer.append(",");
            }
        }
        goodsPublicParam.setImg(stringBuffer.toString());
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                images.clear();
                images.addAll((ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS));
                if (images.size() > 0) {
                    hsvPhotoList.setVisibility(View.VISIBLE);
                    tvAddPhoto.setVisibility(View.GONE);
                } else {
                    hsvPhotoList.setVisibility(View.GONE);
                    tvAddPhoto.setVisibility(View.VISIBLE);
                }
                photoAdapter = new VillagePublishHeaderPhotoAdapter(mContext, images, mHandler);
                recyPhotoList.setAdapter(photoAdapter);
                for (int i = 0; i < images.size(); i++) {
                    lubanImg(images.get(i).path);
                }
            } else {
                Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == IntConstants.FRESHSELECTCASSIFYID) {
            goodTypeId = data.getIntExtra(StringConstants.FLEATYPEID, -1);
            String name = data.getStringExtra(StringConstants.FLEATYPE);
            if (EmptyUtils.isNotEmpty(name)) {
                tvGoodType.setText(name);
            }
            if (goodTypeId != -1) {
                goodsPublicParam.setCat(goodTypeId);
            }
        }
    }

    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public UpLoadPhotoParam uploadPhoto() {
        return loadPhotoParam;
    }

    @Override
    public void uploadData(String urls) {
        imgs.add(urls);
    }

    @Override
    public GoodsPublicParam getFreshGoodParam() {
        return goodsPublicParam;
    }

    @Override
    public void putFreshGoodOnSuccess(List<GoodIdBean> o) {
        if (o.size() > 0) {
            goodIdBean = o.get(0);
        }
        Toast.makeText(mContext, "发布成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(mContext, FreshFruitsGoodDetailActivity.class);
        intent.putExtra(StringConstants.FRESHGOODID, Integer.valueOf(goodIdBean.getId()));
        startActivity(intent);
        mActivity.finish();
    }

    /**
     * 开始加载地址选择器  start
     */
    private void ShowPickerView(final TextView tv) {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(mActivity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
//                String tx = options2Items.get(options1).get(options2);
                Constants.positions.clear();
                Constants.positions = options3Items.get(options1).get(options2);
                tv.setText(tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

//   pvOptions.setPicker(options1Items);//一级选择器
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(mActivity, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);
                        if (Constants.bdLocation != null && CityName.equals(Constants.bdLocation.getCity())) {
                            Constants.positions.add(AreaName);
                        }
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
    /**
     * 开始加载地址选择器  end
     */
}
